package org.gthelper.handler;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;

import org.gthelper.data.DataGeter;
import org.gthelper.database.FileInfo;
import org.gthelper.database.FileStatus;
import org.gthelper.database.UserInfo;
import org.gthelper.error.ErrorCode;
import org.gthelper.hdfs.HdfsMA;
import org.gthelper.order.OrderInfo;

/**
 * 执行用户提交的删除文件命令
 * @author pig
 */
public class Delete extends Handler
{

	@Override
	public int handle(OrderInfo orderinfo) {
		// TODO 自动生成的方法存根
		
		//get id
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataGeter dg = new DataGeter();
		int errcode=dg.getData(orderinfo.orderStream, baos);
		if(errcode!=ErrorCode.NORMAL)return errcode;
		byte[] userid = baos.toByteArray();
		baos.reset();
		String usrId;
		try {
			usrId = new String(userid,"UTF-8");
		
			//get filename
			errcode = dg.getData(orderinfo.orderStream, baos);
			if(errcode!=ErrorCode.NORMAL)return errcode;
			byte[] filename = baos.toByteArray();
			baos.reset();
			String fileName = new String(filename,"UTF-8");
			if((fileName.indexOf('/'))>-1)return ErrorCode.WRONGNAME;
			if((fileName.indexOf('\\'))>-1)return ErrorCode.WRONGNAME;
			try {
				FileInfo fileinfo=FileInfo.getfileInfobyuserIDandfilename(usrId, fileName);
				if((fileinfo==null)||(fileinfo.getstatus()<0))return ErrorCode.FILENOTEXIST;
				if((fileinfo.getstatus()!=FileStatus.normal)&&(fileinfo.getstatus()!=FileStatus.deleting))return ErrorCode.CANTDELETE;
				fileinfo.setstatus(FileStatus.deleting);
				fileinfo.updatefilelist();

				//delete file in hdfs
				HdfsMA ma = new HdfsMA();
				try {
					ma.delete("/"+usrId+"/"+fileName);
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
					return ErrorCode.IOEXC;
				}
				
				if(!ma.isExist("/"+usrId+"/"+fileName))
				{
					FileInfo.delete(usrId, fileName);
					//return delete successfully to user
					DataOutputStream dos = new DataOutputStream(orderinfo.mainOutput);
					dos.writeLong(1);
					dos.flush();
					dos.close();
					UserInfo userinfo = UserInfo.getUserInfobyID(usrId);
					userinfo.setlastcalltime(new Timestamp(System.currentTimeMillis()));
					userinfo.UpdateUserInfo();
				}
				else return ErrorCode.UNKNOWN;
				
			} catch (Exception e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
				return ErrorCode.DATABASEERR;
			}
			
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		return ErrorCode.NORMAL;
	}

}